#!/usr/bin/env python3
# encoding: utf-8
"""
@author: kevin
@contact: evil365@gmail.com
@project : flask
@file: client.py
@time: 2020/8/4 10:12
@license: (C) Copyright 2019-2025, Corporation Limited.
@desc:
"""

import math, time
from app.models.zf_model import product, productinfo, productrepay, clientposion, client, brokerage, MandTor
from .errorCode import ProductAllExist, ProductNotFound, RepayAllFound, RepayNotFound, PosionAllExist, PosionNotFound
from .errorCode import ProdictInfoAllFound, ProdictInfoNotFound, ProdictMandatorAllFound, ProdictMandatorNotFound, ProdictBrokerAllFound, ProdictBrokerNotFound
from sqlalchemy import func


class my_product(product):

    @classmethod
    def get_product_count(cls):
        _count = cls.query.filter_by(delete_time=None).count()
        if not _count:
            raise ProductNotFound()
        return _count

    @classmethod
    def get_all_products(cls, page):
        num = 10
        page = int(page)
        if page == 1:
            skip = 0
        else:
            skip = (page - 1) * num
        product_list = cls.query.with_entities(cls.name, cls.status, cls.assetType, MandTor.name, cls.sn).outerjoin(MandTor).filter_by(delete_time=None).order_by(cls.sn.desc()).order_by(cls.status).limit(num).offset(skip).all()
        count = cls.get_product_count()
        pages = math.ceil(count / num)
        if product_list:
            product_data = []
            for i in product_list:
                date = {'name': i[0], 'status': i[1], 'assetType': i[2], 'mandator': i[3], 'sn': i[4]}
                product_data.append(date)
            product_list = {'list': product_data, 'total': count, 'page': pages}
        else:
            raise ClientNotFound()
        return product_list

    @classmethod
    def get_product_by_name(cls, q):
        _product = cls.query.filter(cls.name.like ('%' + q + '%')).filter_by(delete_time=None).all()
        if not _product:
            raise ProductNotFound()
        return _product

    @classmethod
    def get_product_by_sn(cls, psn):
        _product = cls.query.filter(cls.sn == psn).filter_by(delete_time=None).all()
        if _product is None:
            raise ProductNotFound
        return _product

    @classmethod
    def update_product(cls, psn, form):
        _product = cls.query.filter_by(sn=psn, delete_time=None).first()
        if _product is None:
            raise ProductNotFound
        print(form.data)
        _product.update(
            sn=psn,
            RId=form.RSn.data,
            name=form.name.data,
            status=form.status.data,
            mandatorId=form.mandatorSn.data,
            bookrunnerId=form.bookrunnerSn.data,
            assetType=form.assetType.data,
            commit=True
        )
        return True


    @classmethod
    def get_posion_by_product(cls, psn, page):
        num = 10
        page = int(page)
        result = []
        if page == 1:
            skip = 0
        else:
            skip = (page - 1) * num
        _posion = clientposion.query.with_entities(clientposion.quantity, clientposion.assetType, clientposion.rateSequence, client.userName).outerjoin(client).filter(clientposion.productSn == psn).filter(clientposion.delete_time == None).order_by(clientposion.sn.desc()).limit(num).offset(skip).all()
        count = cls.get_product_count()
        pages = math.ceil(count / num)
        if _posion is None:
            raise PosionNotFound
        quantity = 0
        for i in _posion:
            data = {'quantity': i[0], 'assetType': i[1], 'rateSequence': i[2], 'userName': i[3]}
            result.append(data)
            quantity = quantity + i[0]
        if quantity > 0:
            posion_list = {'list': result, 'total': count, 'page': pages}
            return posion_list
        else:
            return '产品已经全部清算完成'

    @classmethod
    def get_product_info(cls, psn):
        _info = productinfo.query.with_entities(productinfo.quota, productinfo.daysofyear, productinfo.duration, productinfo.precision, productinfo.mode, productinfo.onlineType, productinfo.productType, productinfo.valueStartDate, productinfo.ValueEndDate).filter(productinfo.productSn == psn).filter_by(delete_time=None).all()
        if _info is None:
            raise ProdictInfoNotFound()
        for i in _info:
            info = {'quota': i[0], 'daysofyear': i[1], 'duration': i[2], 'precision': i[3], 'mode': i[4], 'onlineType': i[5], 'productType': i[6], 'valueStartDate': i[7], 'valueEndDate': i[8]}
        return info

    @classmethod
    def get_product_repay(cls, psn):
        _repay = productrepay.query.filter(productrepay.productSn == psn).filter_by(delete_time=None).all()
        if _repay is None:
            raise RepayNotFound()
        return _repay

    @classmethod
    def get_madater(cls):
        result = []
        _mandator = MandTor.query.filter_by(delete_time=None).all()
        if not _mandator:
            raise ProdictMandatorNotFound
        for i in _mandator:
            tmp = {'sn': i.sn, 'name': i.name}
            result.append(tmp)
        return result

    @classmethod
    def get_broker(cls):
        _bro = brokerage.query.filter_by(delete_time=None).all()
        if not _bro:
            raise ProdictBrokerNotFound
        return _bro
